var async = require('async');
var news = require("../controllers/article");
var Category = require("../models/category");
var Banner = require("../models/banner");
var Cases = require("../models/cases");
var Page = require("../models/page");
var Partners = require("../models/_partners");
var News = require("../models/article");
var Download = require("../models/download");
var Comment = require("../models/comment");
var laypage = require("laypage")
var cryptojs = require("crypto-js")
var Category_options = function (arr1, arr2) {
    const _mapArr = []
    arr1.map((item, key) => {
        const options = {id: item.id, name: item.name}
        options.subtype = []
        arr2.map((_item, _key) => {
            if (_item.typeId === item.id && _item.isIndex) {
                options.subtype.push({id: _item.id, title: _item.title})
            }
        })
        options.chlidren = arr2
        _mapArr.push(options)
    })
    // console.log(_mapArr)
    return _mapArr
}
// 首页
exports.index = function (req, res) {
    var coursesType = [{'id': 1, 'name': '特种作业操作证'}, {'id': 2, 'name': '职业资格证'}, {'id': 3, 'name': '建筑类'}, {
        'id': 4,
        'name': '技师/高级技师证'
    }]
    var coursesTypeArr = []
    async.parallel([
            // 导航
            function (cb) {
                Banner.find({}, function (err, banner) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, banner);
                    }
                })
            },
            function (cb) {
                Cases.find({}, function (err, Cases) {
                    if (err) {
                        cb(err);
                    } else {
                        coursesType.forEach(function (item,key) {
                            Cases.forEach(function (_item,_key) {
                                if(_item.typeId === item.id){
                                    coursesTypeArr.push({'id': item.id, 'name': item.name,children:[]})
                                    coursesTypeArr[key].child = item
                                }
                            })
                        })
                        cb(null, Cases);
                    }
                })
            },
            function (cb) {
                Cases.find({'typeId': 1, 'isIndex': true}).limit(4).exec(function (err, _Cases) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, _Cases);
                    }
                })
            },
            function (cb) {
                Cases.find({'typeId': 2, 'isIndex': true}).limit(6).exec(function (err, _Cases) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, _Cases);
                    }
                })
            },
            function (cb) {
                Cases.find({'typeId': 3, 'isIndex': true}).limit(4).exec(function (err, _Cases) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, _Cases);
                    }
                })
            },
            function (cb) {
                News.find({'typeId': 13}).limit(6).exec(function (err, News) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, News);
                    }
                })
            },
            function (cb) {
                News.find({'typeId': 12}).limit(3).exec(function (err, News) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, News);
                    }
                })
            },
            function (cb) {
                News.find({'typeId': 15}).limit(3).exec(function (err, News) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, News);
                    }
                })
            },
            function (cb) {
                News.find({'typeId': 14}).limit(2).exec(function (err, News) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, News);
                    }
                })
            },
            function (cb) {
                Partners.find().exec(function (err, _Partners) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, _Partners);
                    }
                })
            }],
        function (err, results) {
            var banner = results[0],
                CasesArr = results[1],
                CasesArr_1 = results[2],
                CasesArr_2 = results[3],
                CasesArr_3 = results[4],
                inform = results[5],
                news_1 = results[6],
                news_2 = results[7],
                news_3 = results[8],
                partnersList = results[9];
            var _coursesType = Category_options(coursesType,CasesArr)
            res.render('index', {
                banner: banner,
                coursesType: _coursesType,
                CasesArr_1: CasesArr_1,
                CasesArr_2: CasesArr_2,
                CasesArr_3: CasesArr_3,
                inform: inform,
                news_1: news_1,
                news_2: news_2,
                news_3: news_3,
                partnersList: partnersList
            })
        })
}
var decrypt = function (ciphertext){
    var keyHex = cryptojs.enc.Utf8.parse('MdAJYhTz6jrZJ6Qh');
    var decrypted = cryptojs.DES.decrypt({
      ciphertext: cryptojs.enc.Base64.parse(ciphertext)
  }, keyHex, {
      mode: cryptojs.mode.ECB,
      padding: cryptojs.pad.Pkcs7
    })
    return decrypted.toString(cryptojs.enc.Utf8)
  }
exports.ifname = function (req, res) {
    var src= req.originalUrl.split('src=')
    req.header("X-Frame-Options", "allow-from");
     res.render('ifname', {
        ifname: src[1]
    })
}
exports.courses = function (req, res) {
    async.parallel([
            // 课程分类列表
            function (cb) {
                var _id = req.query.id
                Cases.find({"typeId": _id}, function (err, Cases) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, Cases);
                    }
                })
            }],
        function (err, results) {
            var courses = results[0];
            var coursesType = [{'id': 1, 'name': '特种作业操作证'}, {'id': 2, 'name': '职业资格证'}, {
                'id': 3,
                'name': '建筑类'
            }, {'id': 4, 'name': '技师/高级技师证'}]
            if (req.query.type == 'get') {
                res.send({
                    success: true,
                    data: {
                        courses: courses,
                    }
                })
            } else {

                res.render('courses', {
                    courses: courses,
                    $id: req.query.id,
                    coursesType: coursesType
                })
            }
        })

}
exports.coursesShow = function (req, res) {
    async.parallel([
            function (cb) {
                var _id = req.query.id
                Cases.findOne({"id": _id}, function (err, Cases) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, Cases);
                    }
                })
            }, function (cb) {
                var _id = req.query.id
                Comment.find({"cid": _id}, function (err, Comment) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, Comment);
                    }
                })
            }],
        function (err, results) {
            var courses_show = results[0];
            var comment = results[1];
            courses_show.tags = []
            courses_show.tags = courses_show.tag.split(',')
            res.render('courses_show', {
                $SYS: {
                    title: courses_show.title,
                    keywords: '',
                    description: ''
                },
                coursesShow: courses_show,
                commentList: comment,
                $id: req.query.id,
            })
        })

}
// 企业新闻
exports.news = function (req, res) {
    var _id = req.query.tid || 12;
    var pageSize = 10; //每页显示条数
    var page = req.params.num - 1 || 0;
    async.parallel([
            // 新闻列表
            function (cb) {
                News.find({'typeId': _id}).limit(pageSize).skip(pageSize * page).sort({"publish": "desc"}).exec(function (err, news) {
                    if (err) {
                        return cb(err)
                    } else {
                        console.log(news)
                        return cb(null, news)
                    }
                });
            },
            // 新闻类别
            function (cb) {
                Category.find({'original': 1}).exec(function (err, _Category) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Category)
                    }
                });
            },
            //当前新闻类别
            function (cb) {
                Category.findOne({'id': _id}).exec(function (err, _Category) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Category)
                    }
                });
            },
            // 新闻总条数
            function (cb) {
                News.find({'typeId': _id}).count().exec(function (err, sum) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, sum)
                    }
                });
            }],
        function (err, results) {
            var news = results[0],
                newsType = results[1],
                newsListName = results[2],
                sum = results[3];
            res.render('news', {
                $SYS: {
                    title: newsListName.CateName,
                    keywords: '',
                    description: ''
                },
                laypage: laypage({
                    curr: req.params.num || 1,
                    url: req.url, //必传参数，获取当前页的url
                    groups: 9,
                    pages: Math.ceil(sum / pageSize),
                    prev: '‹',
                    next: '›',
                    className: "pages"
                }),
                pagesize: sum,
                newsType: newsType,
                newsList: news,
                newsListName: newsListName
            })
        })
}


// 新闻详情
exports.newsDetail = function (req, res) {
    var _tid = req.query.tid;
    async.parallel([
            // 新闻详情
            function (cb) {
                updateclicks(req.query.id)
                News.findOne({id: req.query.id}).exec(function (err, newsDetail) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, newsDetail)
                    }
                });
            },
            // 新闻类别
            function (cb) {
                Category.find({'original': 1}).exec(function (err, _Category) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Category)
                    }
                });
            },
            //当前新闻类别
            function (cb) {
                Category.findOne({'id': _tid}).exec(function (err, _Category) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Category)
                    }
                });
            },
            // 上一篇，下一篇
            function (cb) {
                var id = req.query.id
                var typeid = req.query.tid
                News.find({'id': {'$lt': id}, "typeId": typeid}).sort({id: 1}).limit(1).exec(function (err, data) {
                    if (err) {
                        cb(err)
                    } else {
                        News.find({
                            'id': {'$gt': id},
                            "typeId": typeid
                        }).sort({id: -1}).limit(1).exec(function (err, _data_) {
                            if (err) {
                                cb(err)
                            } else {
                                var _data = {
                                    pre: {
                                        id: (data.length > 0 && data[0].id) || '',
                                        tid: typeid,
                                        title: (data.length > 0 && data[0].title) || ''
                                    },
                                    next: {
                                        id: (_data_.length > 0 && _data_[0].id) || '',
                                        tid: typeid,
                                        title: (_data_.length > 0 && _data_[0].title) || ''
                                    }
                                }
                                cb(null, _data)
                            }
                        })
                    }
                })
            }],
        function (err, results) {
            var newsDetail = results[0],
                newsType = results[1],
                newsListName = results[2],
                preNext = results[3];
            res.render('newsDetail', {
                $SYS: {
                    title: newsDetail.title,
                    keywords: newsDetail.keywords,
                    description: newsDetail.remark
                },
                newsType: newsType,
                newsListName: newsListName,
                newsDetail: newsDetail,
                preNext: preNext
            })
        })
}

// 联系我们
exports.contactus = function (req, res) {
    res.render('contactus', {
        $SYS: {
            title: '联系我们',
            keywords: '',
            description: ''
        }
    })
}

// 联系我们
exports.aboutus = function (req, res) {
    async.parallel([
            // 关于我们-公司简介
            function (cb) {
                Page.findOne({"_id": '_about_1'}).exec(function (err, newsDetail) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, newsDetail.content)
                    }
                });
            },
            // 关于我们-我们的优势
            function (cb) {
                Page.findOne({'_id': '_about_2'}).exec(function (err, _Category) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Category.content)
                    }
                });
            },
            // 关于我们-荣誉
            function (cb) {
                Page.findOne({'_id': '_about_3'}).exec(function (err, _Category) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Category.content)
                    }
                });
            },
            // 关于我们-合作伙伴
            function (cb) {
                Partners.find().exec(function (err, _Partners) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Partners)
                    }
                });
            }],
        function (err, results) {
            var _about_1 = results[0],
                _about_2 = results[1],
                _about_3 = results[2],
                PartnersList = results[3];
            res.render('aboutus', {
                $SYS: {
                    title: '关于我们',
                    keywords: '',
                    description: ''
                },
                _about_1: _about_1,
                _about_2: _about_2,
                _about_3: _about_3,
                PartnersList: PartnersList
            })
        })
}
// 搜索
exports.search = function (req, res) {
    var pageSize = 10; //每页显示条数
    var keyword = req.query.keyword
    var page = req.params.num - 1 || 0;
    var query = {};
    if (keyword) {
        query['title'] = new RegExp(keyword, 'i')
    }
    Cases.find(query).count().exec(function (err, sum) {
        Cases.find(query).limit(pageSize).skip(pageSize * page).sort({_id: -1}).exec( function (err, _searchList) {
            if (err) {
                cb(err);
            } else {
                res.render('search', {
                    $SYS: {
                        title: '搜索',
                        keywords: '',
                        description: ''
                    },
                    laypage: laypage({
                        curr: req.params.num || 1,
                        url: req.url, //必传参数，获取当前页的url
                        groups: 5,
                        pages: Math.ceil(sum/pageSize), //分页总数你需要通过sql查询得到
                        prev: '‹',
                        next: '›',
                        className: "pages"
                    }),
                    searchList: _searchList,
                    pagesize: sum
                })
            }
        })
    })
}
//获取浏览次数
var updateclicks = function (id) {
    News.update({"id": id}, {$inc: {clicks: 1}}, function (err) {
        if (err) {
            console.log(err);
        }
    });
}

// 企业新闻
exports.download = function (req, res) {
    var pageSize = 10; //每页显示条数
    var page = req.params.num - 1 || 0;
    async.parallel([
            // 新闻列表
            function (cb) {
                Download.find().limit(pageSize).skip(pageSize * page).sort({"publish": "desc"}).exec(function (err,_Download) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, _Download)
                    }
                });
            }, // 新闻总条数
            function (cb) {
                Download.find().count().exec(function (err, sum) {
                    if (err) {
                        return cb(err)
                    } else {
                        return cb(null, sum)
                    }
                });
            }],
        function (err, results) {
            var downloadList = results[0],
                sum = results[1];
            res.render('download', {
                $SYS: {
                    title: '资料下载',
                    keywords: '',
                    description: ''
                },
                laypage: laypage({
                    curr: req.params.num || 1,
                    url: req.url, //必传参数，获取当前页的url
                    groups: 9,
                    pages: Math.ceil(sum / pageSize),
                    prev: '‹',
                    next: '›',
                    className: "pages"
                }),
                downloadList: downloadList,
                pagesize: sum
            })
        })
}
